__author__ = 'st316'
'''
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.

If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.

You may not alter the values in the nodes, only nodes itself may be changed.

Only constant memory is allowed.

For example,
Given this linked list: 1->2->3->4->5

For k = 2, you should return: 2->1->4->3->5

For k = 3, you should return: 3->2->1->4->5
'''


# Definition for singly-linked list.
class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

    def toString(self):
        cur = self
        s = ''
        while cur.next:
            s += str(cur.val) + ' -> '
            cur = cur.next
        return s + str(cur.val)


class Solution:
    # @param head, a ListNode
    # @param k, an integer
    # @return a ListNode
    def reverseKGroup(self, head, k):
        if k <= 1 or not head:
            return head
        n = 0
        hh = head
        tail = None
        h = head
        p = head
        while p:
            n += 1
            if n == k:
                q = p.next
                p.next = None
                res = self.reverse(h)
                if tail:
                    tail.next = res[0]
                else:
                    hh = res[0]
                tail = res[1]
                h = q
                p = q
                n = 0
            else:
                p = p.next
        if n != k and tail:
            tail.next = h
        return hh

    def reverse(self, head):
        if not head or not head.next:
            return head, head
        tail = head
        p = head
        q = p.next
        p.next = None
        while q:
            tmp = q.next
            q.next = p
            p = q
            q = tmp
        return p, tail


if __name__ == '__main__':
    l = [1, 2, 3, 4, 5]
    l1 = ListNode(l[0])
    cur1 = l1
    for v in l[1:]:
        cur1.next = ListNode(v)
        cur1 = cur1.next
    s = Solution()
    print s.reverseKGroup(l1, 2).toString()